<template>
  <div :class="$style.newlist">
    {{ newsList.length }}
    <span>条数据</span>
    <div style="display: flex">
      <div
        ref="scrollContainer"
        :class="[$style.area]"
        style="height: 720px; width: 500px; padding: 10px"
      >
        <a-spin :spinning="spinning">
          <div
            v-if="showArr.length === 0"
            style="width: 500px; height: 500px"
          ></div>
          <div
            v-for="item in showArr"
            v-else
            :key="item.id"
            :class="$style.newsList"
          >
            <NewsItem :new-item="item" />
          </div>
        </a-spin>
      </div>
      <a-button type="primary" style="margin-left: 10px" @click="refreshData">
        刷新
      </a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import NewsItem from '@/components/news-item.vue';
import { onMounted, onUnmounted, ref } from 'vue';
import { getNews, NewItem } from '@/api';
import { useFormatTime } from '@/utils/hooks';
import { useDebounceFn } from '@vueuse/core';
const newsList = ref<NewItem[]>([]);
const spinning = ref<boolean>(false);
const getList = async () => {
  try {
    spinning.value = true;
    const { data } = await getNews();
    spinning.value = false;
    newsList.value = data.news.map((v: NewItem) => {
      return {
        ...v,
        publish_time: useFormatTime(v.publish_time, 'YYYY-MM-DD HH:mm'),
      };
    });
    showArr.value = newsList.value.slice(0, 10);
    if (scrollContainer.value) {
      scrollContainer.value.scrollTop = 0;
    }
  } catch {
    spinning.value = false;
    return false;
  }
};
onMounted(() => {
  getList();
  scrollContainer.value?.addEventListener('scroll', handleScroll);
});
onUnmounted(() => {
  scrollContainer.value?.removeEventListener('scroll', handleScroll);
});
const page = ref(1);
const scrollContainer = ref();
const showArr = ref<NewItem[]>([]);
const fetchData = () => {
  page.value += 1;
  if (page.value <= Math.ceil(newsList.value.length / 10)) {
    const arr = newsList.value.slice((page.value - 1) * 10, page.value * 10);
    showArr.value = showArr.value.concat(arr);
  }
};
// 监听滚动的逻辑
const handleScroll = () => {
  const { scrollTop, scrollHeight, clientHeight } = scrollContainer.value;
  // 当滚动到底部时加载更多
  if (scrollTop + clientHeight + 20 >= scrollHeight) {
    fetchData();
  }
};
const refreshData = useDebounceFn(() => {
  getList();
}, 300);
</script>

<style module lang="less">
.newlist {
  .area {
    border-radius: 5px;
    border: 1px solid rgba(5, 5, 5, 0.06);
    overflow-y: auto;
    overflow-x: hidden;
  }
  .newsList {
    margin-top: 10px;
    &:first-child {
      margin-top: 0;
    }
  }
}
</style>
